package assignmentImplementation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import keyValueBaseInterfaces.ValueSerializer;

public class ValueSerializerImpl implements ValueSerializer<ValueListImpl> {

	// we could make a constructor that takes the value of the key
	// since this is currently violating the one partial key-value mapping per line
	// since separation is happening per line but no key is being introduced.
	
	public ValueListImpl fromByteArray(byte[] array) throws IOException {
		
		ArrayList<byte[]> a = new ArrayList<byte[]>();
		
		
		int length = 0;
		int start = 0;
		
		for(int i=0; i<array.length; i++){
			
			if(array[i] != " ".getBytes()[0]){
				length++;
			}
			else{
				
				byte[] b = new byte[length]; 
				
				for(int j=0; j<length; j++){
					b[j] = array[j+start];
				}
				a.add(b);
				start += length + 1; // to include the whitespace
				length = 0;
			}
			
		}
			
		ValueListImpl vli = new ValueListImpl();
		for(int i=0; i<a.size(); i++){
			ValueImpl v = new ValueImpl();
			v.setValue(new String(a.get(i)));
			vli.add(v);
		}
		
		return vli;
	}

	public byte[] toByteArray(ValueListImpl v) throws IOException {
		
		Iterator<ValueImpl> iter = v.iterator();
		ArrayList<byte[]> a = new ArrayList<byte[]>();
		
		// using the empty space as an item separator
		while(iter.hasNext()){
			a.add(
					(iter.next().toString() + " "
							).getBytes());
		}
		
		int size = 0;
		for(int i=0; i<a.size(); i++)
			size += a.get(i).length;
		
		byte[] b = new byte[size];
		
		int counter = 0;
		for(int i=0; i<a.size(); i++){
			byte[] aB = a.get(i);
			for(int j=0; j<aB.length; j++){
				b[counter+j] = aB[j];
			}
			counter += aB.length;
		}
		return b;
	}

}
